#include <vector>
#include <boost/lexical_cast.hpp>
#include <config/NovelConfig.h>
#include <utils/XString.h>
#include <exception/NpException.h>
#include "AnalyseContents.h"

#define DEFAULT_CHAPTER_NAME "待定"
//#define TEST 1

using namespace  std;
using namespace ruleconfiguration;
using namespace npexception;
AnalyseContents::AnalyseContents()
{

}

chapterInfo::ChapterInfo& AnalyseContents::operator [](int index)
{
  throwExIf(index < 0 || index >= m_bookReaderIndex, INVALID_LIST_INDEX);
  return m_bookreader[index];
}

void AnalyseContents::analyseVolumeList()
{
  //先将目录页的HTML切断成多个卷内容
  //1.qidian用正则分割,其他可以用find方法分割
  //2.发现卷后存入list,为后续chapter.volumeid
  m_bookReaderIndex = 0;
  m_chapterID= 1;
  vector<string> volumes;
  splitVolumeHtml(volumes);
  for(size_t i=1; i< volumes.size();++i)
  {
    //    cout<<volumes[i]<<endl;
    analyseVolume(volumes[i]);

    analyseChapterList(volumes[i], m_bookreader[m_bookReaderIndex -1 ]);
  }
}

void AnalyseContents::analyseVolume(const string& volumeString)
{
  RegexInfo* regVolume = m_rule.getRegex("PubVolumeName");
  boost::regex regexVolume(regVolume->Pattern);
  std::string::const_iterator itr_begin = volumeString.begin();
  std::string::const_iterator itr_end = volumeString.end();
  boost::smatch matchs;
  if(boost::regex_search(itr_begin, itr_end, matchs, regexVolume, regVolume->Options))
  {
    chapterInfo::ChapterInfo  chapter;
    chapter.articleid = m_article.articleid;
    chapter.articlename = m_article.articlename;
    //chapter.chapterid = boost::lexical_cast<string>(NovelConfig::getInstance()->getMaxChapterID());
    chapter.chapterid = boost::lexical_cast<string>(  m_chapterID);
    m_chapterID++;
    chapter.chaptername = matchs[1];
    chapter.chapterorder =boost::lexical_cast<string>(m_bookReaderIndex);  //序号
    chapter.chaptertype = '1';                  //卷
    m_bookreader[m_bookReaderIndex] = chapter;
    m_bookReaderIndex++;

    itr_begin = matchs[0].second;
  }
}

void AnalyseContents::analyseChapterList(const string& volumeString, const  chapterInfo::ChapterInfo& volume)
{
  RegexInfo* regChapterName = m_rule.getRegex("PubChapterName");
  boost::regex regexChapterName(regChapterName->Pattern);
  std::string::const_iterator itr_begin = volumeString.begin();
  std::string::const_iterator itr_end = volumeString.end();
  boost::smatch matchs;
  int posBegin = m_bookReaderIndex;
  //分析chater名称
#ifdef TEST
  int nameCounter =0;
  int linkCounter = 0;
#endif
  while(boost::regex_search(itr_begin, itr_end, matchs, regexChapterName, regChapterName->Options))
  {
    chapterInfo::ChapterInfo  chapter;
    chapter.articleid = m_article.articleid;
    chapter.articlename = m_article.articlename;
    // chapter.chapterid = boost::lexical_cast<string>(NovelConfig::getInstance()-> getMaxChapterID());
    chapter.chapterid = boost::lexical_cast<string>(  m_chapterID);
    m_chapterID++;
    chapter.chaptername = matchs[1];
    if(regChapterName->FilterPattern.empty() == false)
    {
      XString::replaceAll( chapter.chaptername,regChapterName->FilterPattern,"");
    }
#ifdef TEST
    nameCounter++;
    std::cout<< chapter.chaptername<<std::endl;
#endif
    chapter.chapterorder =boost::lexical_cast<string>(m_bookReaderIndex);  //序号
    chapter.chaptertype = '0';                    //章
    chapter.isnew ='1';
    chapter.ctype = "0";        //默认为文字章节，采集到附件时再修改成为图片类型
    chapter.volumeid = volume.chapterid;
    m_bookreader[m_bookReaderIndex] = chapter;
    m_bookReaderIndex++;
    itr_begin = matchs[0].second;
  }
#ifdef  TEST
  std::cout<< "nameCounter:"<<nameCounter<<std::endl;
#endif
  //分析chapter链接
  RegexInfo* regVipFlag = m_rule.getRegex("GetSiteName");
  RegexInfo* regChapterKey = m_rule.getRegex("PubChapter_GetChapterKey");
  boost::regex regexChapterKey(regChapterKey->Pattern);
  RegexInfo* regChapterUrl = m_rule.getRegex("PubContentUrl");
  itr_begin = volumeString.begin();
  itr_end = volumeString.end();
  while(boost::regex_search(itr_begin, itr_end, matchs, regexChapterKey, regChapterKey->Options))
  {
    if(posBegin>= m_bookReaderIndex)
    {
      throw(ANALYSE_CHAPTERLINK_ERROR);
    }
    //有的章节在原站点没有章节名称，给赋个默认章节名
    if(m_bookreader[posBegin].chaptername.length() == 0)
    {
      m_bookreader[posBegin].chaptername = DEFAULT_CHAPTER_NAME;
    }
    m_bookreader[posBegin].contentsLink.assign(regChapterUrl-> Pattern);
    XString::replaceAll(m_bookreader[posBegin].contentsLink, "{ChapterKey}", matchs[1]);
    if(m_bookreader[posBegin].contentsLink.find("{NovelKey}") != string::npos)
    {
      XString::replaceAll(m_bookreader[posBegin].contentsLink, "{NovelKey}", m_article.contentsLink);
    }
#ifdef TEST
    linkCounter++;
    std::cout<< m_bookreader[posBegin].contentsLink<<std::endl;
#endif
    //将vip的规则写在GetSiteName规则节点
    if(m_bookreader[posBegin].contentsLink.find(regVipFlag->Pattern) != string::npos)
    {
      m_bookreader[posBegin].isvip = '1';
    }
    else
    {
      m_bookreader[posBegin].isvip = '0';
    }
    posBegin++;
    itr_begin = matchs[0].second;
  }
#ifdef TEST
  std::cout<< "linkCounter:"<<linkCounter<<std::endl;
#endif
}

void AnalyseContents::splitVolumeHtml(vector<string>& volumes)
{
  RegexInfo* regSplit = m_rule.getRegex("PubVolumeSplit");
  unsigned int posBegin = 0;
  int pos = -1;
  if(regSplit->Method == "Match")
  {
    std::string::const_iterator itr_begin = m_content.begin();
    std::string::const_iterator itr_end = m_content.end();
    boost::smatch matchs;
    boost::regex regexExpress(regSplit->Pattern);
    string findResult;
    while(boost::regex_search(itr_begin, itr_end, matchs, regexExpress, regSplit->Options))
    {
      findResult = matchs[1];
      pos = m_content.find(findResult, posBegin);
      if(pos>=0)
      {
        volumes.push_back(m_content.substr(posBegin,  pos - posBegin));
      }
      itr_begin = matchs[0].second;
      posBegin = pos;
    }
    volumes.push_back(m_content.substr(posBegin, m_content.length() - posBegin));
  }
  else//Split
  {
    while(posBegin < m_content.length())
    {
      pos = m_content.find(regSplit->Pattern, posBegin);
      if(pos >= 0)
      {
        volumes.push_back(m_content.substr(posBegin, m_content.length() - pos - posBegin));
      }
      posBegin = pos;
    }
    volumes.push_back(m_content.substr(posBegin, m_content.length() - posBegin));
  }
}

void AnalyseContents::setChapterID(int index, int id)
{
  m_bookreader[index].chapterid = boost::lexical_cast<string>(id);
}

//void AnalyseContents::setChapterType(int index, char ctype)
//{
//   m_bookreader[index].ctype = ctype;
//}
